package com.loongtech.bi.action.flow;

import com.loongtech.bi.action.Base2BiSearchAction;
import com.loongtech.bi.action.UIHelper;
import com.loongtech.bi.entity.flow.AddcashAndConsumeRankModel;
import com.loongtech.bi.manager.flow.HadoopQueryManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.util.*;
import java.util.Map.Entry;

/**
 * 流水任务充值排行流水Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("view")
public class RechargeRankingFlowAction extends Base2BiSearchAction {
	private static final long serialVersionUID = 1L;
    protected Date day = new Date(Time.getBeginningOfDay(Time.currentTime() - 1 * Time.DAY));
	private RechargeRankingFlow queryBean;  // 查询bean
	private Map<String,AddcashAndConsumeRankModel> tmpMap = new HashMap<String,AddcashAndConsumeRankModel>();
	
	private List<Object[]> consumeResult; //消耗结果List
	
	private List<Object[]> addcashResult;  //充值结果List
	private List<AddcashAndConsumeRankModel> result; //结果
	private Map<String, String> typeItmes; // 货币类型
	private Map<String, String> typeItmesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.CURRENCY_TYPE); //MoneyTypeManager.reasonItmesRevise;  // 货币类型反转

	@Autowired
	private HadoopQueryManager hadoopQueryManager;
	
	@Autowired
	private SysLogManager sysLogManager;
	@Autowired
	private Session session;
	
	@PostConstruct
	public void init() {
		queryBean = new RechargeRankingFlow();
		addcashResult = new ArrayList<>();
		consumeResult = new ArrayList<>();
		result = new ArrayList<>();
		tmpMap = new HashMap<>();
		typeItmes = new HashMap<>();
		for (Entry<String,String> entry : GameParamConfigManager.getItems(CommonGameParam.CURRENCY_TYPE).entrySet()) {
			if (!"全部".equals(entry.getKey())) {
				typeItmes.put(entry.getKey(), entry.getValue());
			}
		}
	}
	
	// 元宝类型
	public String getMoneyType(Object currencyType) {
		String key = currencyType == null ? "" : Math.abs(Integer.parseInt(currencyType.toString())) + "";
		return (typeItmesRevise.get(key) == null) ? key : typeItmesRevise.get(key); 
	}

    public String getMoney(Long addType){
        return null != addType ? UIHelper.getYuan(Double.valueOf(addType)) + "" : "";
    }

	public void search()  {
		sysLogManager.addLog(session.getUserName(), "查询流水查询—任务充值排行流水");
		
		addcashResult = new ArrayList<>();
		consumeResult = new ArrayList<>();
		result = new ArrayList<>();
		tmpMap = new HashMap<>();
		
		FacesContext context = FacesContext.getCurrentInstance();
		
		if (HadoopQueryManager.VISIT_QUEUE.offer("RechargeRankingFlowAction")) {
			System.out.println("VISIT_QUEUE offer RechargeRankingFlowAction ok!");
			
			StringBuffer sql1 = new StringBuffer();
			sql1.append("select serverid,userid,sum(wholecashadd) as totalcash from totalroleaddcash where userid != '' and dt = '"+ Time.getDateStr(day) +"'");
			
			if (!"0".equals(queryServer)) {
				sql1.append(" and serverid = ");
				sql1.append(queryServer);
			}
			
			sql1.append(" group by serverid,userid order by totalcash desc limit 10000 ");
			
			Entry<List<String>, List<Object[]>> ret1 = hadoopQueryManager.executeSQL(sql1.toString());
			if (null == ret1 || null == ret1.getKey() || ret1.getKey().isEmpty() || null == ret1.getValue()) {
				context.addMessage(null, new FacesMessage("提示", "查询结果为空!"));
				return;
			}
			
			addcashResult = ret1.getValue();
			//充值排行
			long addcashIndex  = 0;
			//充值
			for(Object[] obj : addcashResult) {
				AddcashAndConsumeRankModel model = new AddcashAndConsumeRankModel();
				model.setAddcashIndex(++addcashIndex);
				model.setAddcashServerid(String.valueOf(obj[0]));
				model.setAddcashUserid(String.valueOf(obj[1]));
				model.setWholecashadd((long) Double.parseDouble(String.valueOf(obj[2])));
				//加入
				result.add(model);
			}
			
			//消耗查询
			StringBuffer sql2 = new StringBuffer();
			sql2.append("select currencytype,userid,sum(wholeconsume) as totalconsume from totalrolecurrencyconsume where dt = '"+ Time.getDateStr(day) +"' ");
			
			// 增加服务器条件
			if (!"0".equals(queryServer)) {
				sql2.append(" and serverid = ");
				sql2.append(queryServer);
			}
			
			// 增加钻石类型条件
			if (queryBean.getCurrencytype() != -99999) {
				sql2.append(" and currencytype = ");
				sql2.append(queryBean.getCurrencytype());
			}
			
			sql2.append(" group by currencytype,userid order by totalconsume asc limit 1000 ");
			
			Entry<List<String>, List<Object[]>> ret2 = hadoopQueryManager.executeSQL(sql2.toString());
			if (null == ret2 || null == ret2.getKey() || ret2.getKey().isEmpty() || null == ret2.getValue()) {
				context.addMessage(null, new FacesMessage("提示", "查询结果为空!"));
				return;
			}
			
			consumeResult = ret2.getValue();
			
			//消费排行
			long consumeIndex  = 0;
			
			for(Object[] obj : consumeResult) {
				AddcashAndConsumeRankModel model = new AddcashAndConsumeRankModel();
				model.setConsumeIndex(++consumeIndex);
				model.setComnsumeCurrencytype(Integer.parseInt(String.valueOf(obj[0])));
				model.setConsumeUserid(String.valueOf(obj[1]));
				model.setWholeconsume(Long.parseLong(String.valueOf(obj[2])));
				//存入
				tmpMap.put(String.valueOf(obj[1]), model);
			}
			
			//迭代
			for(AddcashAndConsumeRankModel model:result) {
				//充值的user id
				String addcashUserid = model.getAddcashUserid();
				//
				AddcashAndConsumeRankModel tmpModel = tmpMap.get(addcashUserid);
				
				if(tmpModel != null) {
					model.setConsumeIndex(tmpModel.getConsumeIndex());
					model.setComnsumeCurrencytype(tmpModel.getComnsumeCurrencytype());
					model.setConsumeUserid(tmpModel.getConsumeUserid());
					model.setWholeconsume(tmpModel.getWholeconsume());
				}
			}
		} else {
			System.out.println("VISIT_QUEUE offer RechargeRankingFlowAction failed!");
			context.addMessage(null, new FacesMessage("提示", "当前系统正被访问，为保证服务器稳定，请稍后再试"));
			return;
		}
	}
	
	public class RechargeRankingFlow {
		private String logtime; // 时间
		private String hostname; // 服务器主机名
		private String modulename; // 模块名
		private int gameid; // 游戏ID
		private int serverid; // 服务器ID
		private long logid; // 日志编号
		private String logtype; // 日志类型
		private int platform; // 平台ID
		private String channel; // 渠道标识
		private String mac; // 设备mac地址
		private String userid; // 角色ID
		private int rolelevel; // 角色等级
		private int mapid; // 地图ID
		private long rolekiller; // 杀手ID
		private int monsterkiller; // 怪物模板ID
		private int currencytype = -99999; // 货币类型
		
		public String getLogtime() {
			return logtime;
		}

		public void setLogtime(String logtime) {
			this.logtime = logtime;
		}

		public String getHostname() {
			return hostname;
		}

		public void setHostname(String hostname) {
			this.hostname = hostname;
		}

		public String getModulename() {
			return modulename;
		}

		public void setModulename(String modulename) {
			this.modulename = modulename;
		}

		public int getGameid() {
			return gameid;
		}

		public void setGameid(int gameid) {
			this.gameid = gameid;
		}

		public int getServerid() {
			return serverid;
		}

		public void setServerid(int serverid) {
			this.serverid = serverid;
		}

		public long getLogid() {
			return logid;
		}

		public void setLogid(long logid) {
			this.logid = logid;
		}

		public String getLogtype() {
			return logtype;
		}

		public void setLogtype(String logtype) {
			this.logtype = logtype;
		}

		public int getPlatform() {
			return platform;
		}

		public void setPlatform(int platform) {
			this.platform = platform;
		}

		public String getChannel() {
			return channel;
		}

		public void setChannel(String channel) {
			this.channel = channel;
		}

		public String getMac() {
			return mac;
		}

		public void setMac(String mac) {
			this.mac = mac;
		}

		public String getUserid() {
			return userid;
		}

		public void setUserid(String userid) {
			this.userid = userid;
		}

		public int getRolelevel() {
			return rolelevel;
		}

		public void setRolelevel(int rolelevel) {
			this.rolelevel = rolelevel;
		}

		public int getMapid() {
			return mapid;
		}

		public void setMapid(int mapid) {
			this.mapid = mapid;
		}

		public long getRolekiller() {
			return rolekiller;
		}

		public void setRolekiller(long rolekiller) {
			this.rolekiller = rolekiller;
		}

		public int getMonsterkiller() {
			return monsterkiller;
		}

		public void setMonsterkiller(int monsterkiller) {
			this.monsterkiller = monsterkiller;
		}

		public int getCurrencytype() {
			return currencytype;
		}

		public void setCurrencytype(int currencytype) {
			this.currencytype = currencytype;
		}
	}

	@Override
	protected String csvContent() {
		return null;
	}

	@Override
	protected String csvFileName() {
		return null;
	}

	public Date getDateStart() {
		return dateStart;
	}

	public void setDateStart(Date dateStart) {
		this.dateStart = dateStart;
	}

	public RechargeRankingFlow getQueryBean() {
		return queryBean;
	}

	public void setQueryBean(RechargeRankingFlow queryBean) {
		this.queryBean = queryBean;
	}

	public List<AddcashAndConsumeRankModel> getResult() {
		return result;
	}

	public void setResult(List<AddcashAndConsumeRankModel> result) {
		this.result = result;
	}

	public Map<String, String> getTypeItmes() {
		return typeItmes;
	}

	public void setTypeItmes(Map<String, String> typeItmes) {
		this.typeItmes = typeItmes;
	}
}
